package com.example.demo.controller;

import com.example.demo.model.Goods;
import com.example.demo.result.Result;
import com.example.demo.server.GoodsServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsServer goodsServer;

    //查询
    @GetMapping
    public Result list() {
        try {
            List<Goods> goodsList = (List<Goods>) goodsServer.list();
            return Result.success(goodsList);
        } catch (Exception e) {
            return Result.error("查询失败");
        }
    }

    @PostMapping("/add")
    public Result add(@RequestBody Goods goods) {
        try {
            goodsServer.add(goods);
            return Result.success();
        } catch (Exception e) {
            return Result.error("增加数据失败");
        }
    }

    @DeleteMapping("/delete/{number}")
    //按编号删除
    public Result delete(@PathVariable Integer number) {
        try {
            goodsServer.delete(number);
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除数据失败");
        }

    }

    @PutMapping("/update/{targetnumber}")
    //按编号来修改数据
    public Result update(@RequestBody Goods goods, @PathVariable Integer targetnumber) {
        try {
            goodsServer.update(goods, targetnumber);
            return Result.success();
        } catch (Exception e) {
            return Result.error("修改数据失败");
        }
    }

    //条件查询（通过编号来查询）
    @GetMapping("/select/{number}")
    public Result select(@PathVariable Integer number) {
        try {
            List<Goods> goodsList = goodsServer.select(number);
            return Result.success(goodsList);
        } catch (Exception e) {
            return Result.error("查询该编号数据失败");
        }
    }
}
